package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TAddress;
import com.ruoyi.business.service.ITAddressService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * App端 收货地址接口
 *
 * @author laoguo
 */
@RestController
@RequestMapping("/app/address")
public class AppAddressController extends BaseController {

    @Autowired
    private ITAddressService addressService;

    /**
     * 2.1 获取我的收货地址列表
     */
    @GetMapping("/list")
    public AjaxResult list() {
        Long userId = SecurityUtils.getUserId();
        TAddress queryParam = new TAddress();
        queryParam.setUserId(userId);
        // 按是否默认降序、更新时间降序排列
        List<TAddress> list = addressService.selectTAddressList(queryParam);
        return AjaxResult.success(list);
    }

    /**
     * 2.2 新增收货地址
     */
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TAddress address) {
        address.setUserId(SecurityUtils.getUserId());
        address.setCreateBy(SecurityUtils.getUsername());
        // 如果新增的地址是默认地址，需要将该用户其他地址设为非默认
        if ("Y".equals(address.getIsDefault())) {
            addressService.cancelOtherDefaultAddress(address.getUserId());
        }
        return toAjax(addressService.insertTAddress(address));
    }

    /**
     * 2.3 获取单个收货地址详情
     */
    @GetMapping("/{addressId}")
    public AjaxResult getInfo(@PathVariable("addressId") Long addressId) {
        TAddress address = addressService.selectTAddressByAddressId(addressId);
        // 安全校验：确保用户只能获取自己的地址
        if (address == null || !address.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("地址不存在或无权访问");
        }
        return AjaxResult.success(address);
    }

    /**
     * 2.4 修改收货地址
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TAddress address) {
        // 安全校验：防止越权修改别人的地址
        TAddress oldAddress = addressService.selectTAddressByAddressId(address.getAddressId());
        if (oldAddress == null || !oldAddress.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("地址不存在或无权操作");
        }

        address.setUserId(SecurityUtils.getUserId());
        address.setUpdateBy(SecurityUtils.getUsername());
        // 如果将此地址设为默认，需要将该用户其他地址设为非默认
        if ("Y".equals(address.getIsDefault())) {
            addressService.cancelOtherDefaultAddress(address.getUserId());
        }
        return toAjax(addressService.updateTAddress(address));
    }

    /**
     * 2.5 删除收货地址
     */
    @DeleteMapping("/{addressId}")
    public AjaxResult remove(@PathVariable("addressId") Long addressId) {
        // 安全校验
        TAddress address = addressService.selectTAddressByAddressId(addressId);
        if (address == null || !address.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("地址不存在或无权操作");
        }
        return toAjax(addressService.deleteTAddressByAddressId(addressId));
    }

    /**
     * 2.6 (补充) 设置为默认地址
     */
    @PutMapping("/default/{addressId}")
    public AjaxResult setDefault(@PathVariable("addressId") Long addressId) {
        // 安全校验
        TAddress address = addressService.selectTAddressByAddressId(addressId);
        if (address == null || !address.getUserId().equals(SecurityUtils.getUserId())) {
            return AjaxResult.error("地址不存在或无权操作");
        }

        Long userId = SecurityUtils.getUserId();
        // 1. 先将该用户所有地址设为非默认
        addressService.cancelOtherDefaultAddress(userId);
        // 2. 再将指定地址设为默认
        address.setIsDefault("Y");
        return toAjax(addressService.updateTAddress(address));
    }
}